package lancs.mobilemedia.core.ui.controller;

import javax.microedition.lcdui.Command;

import lancs.mobilemedia.core.ui.MainUIMidlet;
import lancs.mobilemedia.core.ui.datamodel.AlbumData;
import lancs.mobilemedia.core.ui.screens.AlbumListScreen;
import lancs.mobilemedia.core.util.Constants;

public class BaseController extends AbstractController {

	private ControllerCommand command;
	private ControllerMapper mapper;

	public BaseController(MainUIMidlet midlet, AlbumData model, AlbumListScreen albumListScreen) {
		super(midlet, model, albumListScreen);
		init();
	}

	public void init() {
		createControllerMapper();
	}

	public void createControllerMapper() {
		mapper = new BaseControllerMapper();
	}

	public boolean handleCommand(Command c) {

		String label = c.getLabel();
		System.out.println(this.getClass().getName() + "::handleCommand: " + label);

		command = (ControllerCommand) mapper.getCommand(label);

		if (command != null) {
			return command.execute(this);
		}
		return false;
	}

	public boolean goToPreviousScreen() {
	    System.out.println("<* AlbumController.goToPreviousScreen() *>");
		String currentScreenName = ScreenSingleton.getInstance().getCurrentScreenName();
		if ( (currentScreenName.equals(Constants.IMAGELIST_SCREEN)) || 
				(currentScreenName.equals(Constants.NEWALBUM_SCREEN)) ||
				(currentScreenName.equals(Constants.CONFIRMDELETEALBUM_SCREEN)) ){
			getAlbumListScreen().repaintListAlbum(getAlbumData().getAlbumNames());
			setCurrentScreen( getAlbumListScreen() );
			ScreenSingleton.getInstance().setCurrentScreenName(Constants.ALBUMLIST_SCREEN);
			return true;
		}
    	
		return false;
    }
	
	public void init(AlbumData model) {
		String[] albumNames = model.getAlbumNames();
		for (int i = 0; i < albumNames.length; i++) {
			if (albumNames[i] != null) {
				getAlbumListScreen().append(albumNames[i], null);
			}
		}
		getAlbumListScreen().initMenu();

		setCurrentScreen(getAlbumListScreen());
	}

	public void destroyMidlet(boolean b) {
		midlet.destroyApp(true);
	}
}